<template>
    <div>
        <!-- 搜索卡片  查询条件：姓名、性别、联系电话、职称、学历、家庭住址、生日 -->
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="工 号">
                    <el-input type="text" placeholder="请输入工号" v-model="queryForm.number" size="small"></el-input>
                </el-form-item>
                <el-form-item label="姓 名">
                    <el-input type="text" placeholder="请输入姓名" v-model="queryForm.username" size="small"></el-input>
                </el-form-item>
                <el-form-item label="电 话">
                    <el-input type="text" placeholder="输入联系电话" v-model="queryForm.mobile" size="small"></el-input>
                </el-form-item>
                <el-form-item label="职 称">
                    <el-input type="text" placeholder="输入职称" v-model="queryForm.professional" size="small"></el-input>
                </el-form-item>
                <el-form-item label="学 历">
                    <el-input type="text" placeholder="输入学历" v-model="queryForm.degree" size="small"></el-input>
                </el-form-item>
                <el-form-item label="住 址">
                    <el-input type="text" placeholder="输入家庭住址" v-model="queryForm.address" size="small"></el-input>
                </el-form-item>
                <el-form-item label="性 别">
                    <el-select v-model="queryForm.sex" size="small">
                        <el-option value="男" label="男"></el-option>
                        <el-option value="女" label="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生 日">
                    <el-date-picker value-format="yyyy-MM-dd" size="small" type="date" placeholder="请选择日期" v-model="queryForm.birthday"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
                :data="teacherList"
                v-loading="loading"
                border
                fit
                :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
                :cell-style="{padding:'5px 0px'}"
                @selection-change="handleSelectionChange"
                style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px"></el-table-column>
                <el-table-column label="工 号" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.number }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="姓 名" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.username }}
                    </template>
                </el-table-column>
                <el-table-column label="职 称" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.professional }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="学 历" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.degree }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="电 话" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.mobile }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="住 址" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.address }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="性 别" align="center">
                    <template slot-scope="scope">
                        <span>{{ scope.row.sex }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="生 日" align="center">
                    <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="启 用" align="center">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enable" active-color="#13ce66" 
                            inactive-color="#ff4949" active-value="1" inactive-value="0"  
                            @change="changeEnabled(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操 作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                :current-page="queryForm.pageNum"
                :page-size="queryForm.pageSize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show" width="42%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules="rules" ref="submitForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工 号" prop="number">
                            <el-input type="text" placeholder="请输入工号" v-model="submitForm.number" :readonly="title=='编辑'?true:false"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密 码" prop="password">
                            <el-input type="password" placeholder="请输入密码" v-model="submitForm.password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓 名" prop="username">
                            <el-input type="text" placeholder="请输入姓名" v-model="submitForm.username"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="职 称" prop="professional">
                            <el-input type="text" placeholder="请输入职称" v-model="submitForm.professional"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="学 历" prop="degree">
                            <el-input type="text" placeholder="请输入学历" v-model="submitForm.degree"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电 话" prop="mobile">
                            <el-input type="text" placeholder="请输入联系电话" v-model="submitForm.mobile"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="住 址" prop="address">
                            <el-input type="text" placeholder="请输入家庭住址" v-model="submitForm.address"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性 别" prop="sex">
                            <el-select v-model="submitForm.sex" placeholder="请选择">
                                <el-option v-for="(item, index) in sexList" :key="'sex-' + index" :value="item" :label="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="生 日" prop="birthday">
                            <el-date-picker type="date" placeholder="请选择日期" v-model="submitForm.birthday" value-format="yyyy-MM-dd"></el-date-picker>
                        </el-form-item>
                    </el-col>   
                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right: 40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listTeachers, getTeacher, addTeacher, updateTeacher, deleteTeacher } from '@/api/teacher'
import { parseTime } from '@/utils/date'

export default {
    name: 'Teacher',
    data() {
        //检查密码是否合法
        const checkPassword = (rule,value,callback)=>{
            //要求存在内容且长度必须在6-16位
            if (this.password == null && (value.length > 16 || value.length < 6)){
                return callback(new Error('长度必须在6-16之间'))
            }
            if (this.password != value && (value.length > 16 || value.length < 6)){
                return callback(new Error('长度必须在6-16之间'))
            }
            callback()
        }
        // 检查联系电话是否合法
        const checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback()
            }
            let reg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
            if (!reg.test(value)) {
                return callback(new Error('请输入合法联系电话'))
            }
            callback()
        }
        return {
            loading: true,
            submitForm: {},
            title: "新增",
            show: false,
            total: 120,
            queryForm: {
                pageNum: 1,
                pageSize: 10
            },
            sexList: ['男', '女'],
            selectList: [],
            teacherList: [],
            rules: {
                number: [
                    { required: true, message: '请输入工号', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度必须在6-16之间', trigger: 'blur' }
                ],
                password:[
                    {required:true,message:'请输入密码',trigger:'blur'},
                    {validator:checkPassword,trigger:'blur'}
                ],
                username: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 16, message: '长度必须在2-16之间', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入家庭住址', trigger: 'blur' }
                ],
                degree: [
                    { required: true, message: '请输入学历', trigger: 'blur' }
                ],
                birthday: [
                    { required: true, message: '请选择生日', trigger: 'blur' }
                ],
                professional: [
                    { required: true, message: '请输入职称', trigger: 'blur' }
                ],
               
            },
            password:'',
            headers: {
                Authorization: 'Bearer ' + this.$Cookie.get('login-token')
            }
        }
    },
    // 创建网页后查询调用数据
    created() {
        this.getList()
    },
    methods: {
        // 调用接口提交数据 - 进行添加和编辑操作的弹窗
        handleSubmit() {
            this.$refs['submitForm'].validate((valid) => {
                if (this.fileName) {
                    this.submitForm.avatar = this.fileName
                }
                if (valid) {
                    if (this.submitForm.id) {
                        this.submitForm.updateBy = this.$Cookie.get("username")
                        updateTeacher(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    } else {
                        this.submitForm.createBy = this.$Cookie.get("username")
                        addTeacher(this.submitForm).then(res => {
                            this.show = false
                            this.getList()
                            this.submitForm = {}
                        }).catch(err => {
                            console.log(err)
                        })
                    }
                }
            })
        },
        // 重置搜索
        handleReset() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10
            }
            this.getList()
        },
        // 按条件搜索
        handleSearch() {
            this.queryForm.pageNum = 1
            this.getList()
        },
        // 修改每页大小
        handleSizeChange(pageSize) {
            this.queryForm.pageSize = pageSize
            this.queryForm.pageNum = 1
            this.getList()
        },
        // 当前页修改
        handleCurrentChange(pageNum) {
            this.queryForm.pageNum = pageNum
            this.getList()
        },
        // 调用接口分页查询教师数据
        getList() {
            this.loading = true
            listTeachers(this.queryForm).then(res => {
                this.teacherList = res.data.records
                this.total = res.data.total
                this.loading = false
            }).catch(err => {})
        },
        // 删除 - 调用接口删除记录
        handleDelete(ids) {
            this.$confirm("你确定删除id为" + ids + "的记录吗？", "提示", {
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                type: "warning"
            }).then(() => {
                // 调接口删除
                deleteTeacher(ids).then(res => {
                    // 提示删除成功
                    this.$message("删除成功")
                    // 刷新列表
                    this.getList()
                }).catch(err => {
                    console.log(err)
                })
            }).catch(() => {})
        },
        // 添加 - 打开添加弹窗
        handleAdd() {
            this.show = true
            this.title = "新增"
            this.imageUrl = 'default.jpg'
            this.submitForm = { sex: '男' }
        },
        // 取消 - 关闭弹窗
        handleCancel() {
            this.show = false
        },
        // 编辑 - 打开编辑弹窗
        handleEdit(id) {
            getTeacher(id).then(res => {
                // 调接口获取最新数据
                this.title = "编辑"
                this.show = true
                this.submitForm = res.data
                this.password = res.data.password
            }).catch(err => {
                console.log(err)
            })
        },
        // 批量删除
        handleBatchDelete() {
            if (this.selectList) {
                let ids = this.selectList.map(o => { return o.id })
                console.log('ids---------->', ids)
                this.handleDelete(ids)
            }
        },
        // 多选
        handleSelectionChange(val) {
            this.selectList = val
        },
        // 时间格式化
        formatDate(value, format) {
            return parseTime(new Date(value), format)
        },
        // 修改启用状态
        changeEnabled(data) {
            data.updateBy = this.$Cookie.get("username")
            updateTeacher(data).catch(err => { console.log(err) })
        }
    }
}
</script>
<style scoped>
.el-form-item {
    margin: 10px;
}
</style>